package cn.cjxy.springbootdemo1.controller;

import cn.cjxy.springbootdemo1.domain.Student;
import cn.cjxy.springbootdemo1.domain.User;
import cn.cjxy.springbootdemo1.util.R;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 模拟CRUD操作接口返回示例
 * @author huangjie
 * @date 2025/10/14
 */
@RestController
@RequestMapping("/student")
public class StudentController {
    //用map来作为存储
   private static Map<Long, Object> studentList= new HashMap<>();

    /**
     * 模拟新增
     * @param student
     * @return
     */
   @PostMapping
    public R<User> addStudent(@RequestBody Student student){
       //执行新增
       student.setId(1L);
       //存入map中
       studentList.put(student.getId(),student);
       //返回
       return R.ok("新增学生成功！！");
   }

    /**
     * 查询所有
     * @return
     */
   @GetMapping
    public R<List<User>> getStudents(){
       ArrayList list=new ArrayList();
       //通过map取得所有键，再循环键取值，再将每个值添加到list中
       studentList.keySet().forEach(key->{
           Object o = studentList.get(key);
           list.add(o);
       });
       return R.ok(list);
   }

    /**
     * 修改用户
     * @param student
     * @return
     */
   @PutMapping
    public R<User> updateStudent(@RequestBody Student student){
       //得到id  根据id做修改
       Long id = student.getId();
       //通过id去查到已经存在的学生信息
       Student student1 =(Student) studentList.get(id);
       System.out.println("改完之钱"+student1);
       //修改操作
       student1.setName("李四");
       student1.setAge(18);
       student1.setSex(1);
       System.out.println("改完之后"+student1);
       return R.ok("修改操作成功！！！！！");
   }

    /**
     *
     * @param id
     * @return
     */
   @DeleteMapping
    public R<User> deleteStudent(Long id){
       studentList.remove(id);
       System.out.println(studentList);
       return R.ok("删除成功");
   }
}
